package com.zx.map.service.impl;


import com.alibaba.fastjson.JSON;
import com.kspay.MD5Util;
import com.kspay.cert.CertVerify;
import com.kspay.cert.LoadKeyFromPKCS12;
import com.zx.map.dao.mapper.ThpartyBalanceAutoMapper;
import com.zx.map.dao.model.ThpartyBalanceAuto;
import com.zx.map.service.ThpartyBalanceService;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.SUConstants;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.HttpParamsUtils;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.TmDateUtil;
import com.zx.scp.utils.PropertyUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by bibei on 2017/4/27.
 */
@Service
public class ThpartyBalanceServiceImpl implements ThpartyBalanceService {

	/**
	 * log
	 */
	private static Logger log = Logger
			.getLogger(ThpartyBalanceServiceImpl.class);
	@Autowired
	private ThpartyBalanceAutoMapper thpartyBalanceAutoMapper;

	@Override
	public Map<String, Object> encashMobao(String transAmount, String accNo, String accName) {
	 try {
		 //创建连接
		 URL url = new URL(PropertyUtil.getValue("mobao_encache_url"));
		 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		 connection.setDoOutput(true);
		 connection.setDoInput(true);
		 connection.setRequestMethod("POST");
		 connection.setUseCaches(false);
		 connection.setInstanceFollowRedirects(true);
		 connection.setRequestProperty("Content-Type","application/json; charset=GBK");
		 connection.connect();
		 //POST请求
		 DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		 String orderId="M"+PmpUtils.getOrderNum();
		 Map transData = new HashMap();
		 transData.put("accName", URLEncoder.encode(accName,"GBK")); // 收款人姓名
		 transData.put("accNo", accNo); // 收款人账号
		 transData.put("orderId",orderId ); // 订单号
		 transData.put("transAmount", transAmount); // 交易金额
		 transData.put("transDate", DateUtils.dateToString(new Date(),DateUtils.DATE_TIME_FMT_OTHER)); // 交易日期
		 //私钥证书加密
		 LoadKeyFromPKCS12.initPrivateKey(PropertyUtil.getValue("mobao_encash_pk"), PropertyUtil.getValue("mobao_encash_pwd"));
		 String jsonData=JSON.toJSONString(transData);
		 log.debug("transData:"+jsonData);
		 String  transBody=LoadKeyFromPKCS12.PrivateSign(jsonData);
		 Map paramMap=new HashMap();
		 paramMap.put("transBody", transBody);
		 paramMap.put("businessType", "470000"); // 业务类型
		 paramMap.put("merId", PropertyUtil.getValue("mobao_merId")); // 商户号
		 paramMap.put("versionId", "001"); // 版本号
		 String preStr = HttpParamsUtils.buildPayParams(paramMap,false,true);
		 String signData = MD5Util.MD5Encode(preStr+"&key="+PropertyUtil.getValue("mobao_merkey"));
		 paramMap.put("signData", signData);
		 paramMap.put("signType", "MD5");
		 out.write(JSON.toJSONString(paramMap).getBytes("GBK"));
		 out.flush();
		 out.close();

		 //读取响应
		 BufferedReader reader = new BufferedReader(new InputStreamReader(
				 connection.getInputStream()));
		 String lines;
		 StringBuffer sb = new StringBuffer("");
		 while ((lines = reader.readLine()) != null) {
			 lines = new String(lines.getBytes(), "GBK");
			 sb.append(lines);
		 }
		 reader.close();
		 // 断开连接
		 connection.disconnect();

		 ThpartyBalanceAuto thpartyBalanceAuto = new ThpartyBalanceAuto();
		 thpartyBalanceAuto.setAccName(accName);
		 thpartyBalanceAuto.setAccNo(accNo);
		 thpartyBalanceAuto.setOrderId(orderId);
		 thpartyBalanceAuto.setTransAmount(new BigDecimal(transAmount));
		 thpartyBalanceAuto.setCreateTime(TmDateUtil.nowTime());
		 thpartyBalanceAuto.setStatus(SUConstants.CODE_FAIL_VALUE);
		 Map<String,Object> resMap = JSON.parseObject(sb.toString(), Map.class);
		 log.debug("摩宝T0取现返回："+sb.toString());
		 String refMsg;
		 if(resMap.get("status").equals("00")){
			 String data = resMap.get("resBody").toString();
			 //公钥证书解密
			 CertVerify.initPublicKey(PropertyUtil.getValue("mobao_encash_pubkey"));
			 byte[] str1=CertVerify.publicKeyDecrypt(LoadKeyFromPKCS12.encryptBASE64(data));
			 String res=new String(str1);
			 log.debug("摩宝T0取现返回resBody："+res);
			 Map<String, String> resBody= JSON.parseObject(res,Map.class);
			 refMsg= URLDecoder.decode((String) resBody.get("refMsg"),"GBK");
			 if(resBody.get("refCode").equals("00")) {
				 thpartyBalanceAuto.setStatus(SUConstants.CODE_SUCCESS_VALUE);
			 }
		 } else {
			 refMsg= URLDecoder.decode((String) resMap.get("refMsg"),"GBK");
		 }
		 thpartyBalanceAuto.setMsg(refMsg);
		 thpartyBalanceAutoMapper.insertSelective(thpartyBalanceAuto);
		 return CommonResponseUtils.successResponse(refMsg);
	 } catch (Exception e) {
		 log.debug("摩宝T0取现异常：",e);
		 return CommonResponseUtils.failureResponse();
	 }
	}
}
